import Vue from 'vue';
import toastVue from './Toast.vue';
let ToastContent = Vue.extend(toastVue);

let content, promise;

let Toast = {
  show: function (option) {
    option = option || {}; 

    if (content) DestroyNow(content);



    content = new ToastContent({
      el: document.createElement('div'),
      data: {
        ...option,
        callback: defaultCallback
      }
    })

    // content.vm = content.$mount();
    document.body.appendChild(content.$el);
    Vue.nextTick(() => {
      content.visible = true;
    });
    if (typeof Promise !== 'undefined') {
      return new Promise((resolve, reject) => {
        promise = {
          resolve,
          reject
        }
      });
    } else {
      promise = option.callback
    }
  }
}

Toast.close = function () {
  if (!content) {
    console.warn('Toast not Init');
    return;
  }
  content.vm.visible = false;
}

const defaultCallback = action => {
  let callback = promise.callback;
  if (typeof callback === 'function') {
    callback(action);
  }
  if (promise.resolve) {
    if (action === 'confirm') {
      promise.resolve(action);
    } else {
      promise.reject(action);
    }
  }
};

const DestroyNow = (content) => {
  content.$el.remove();
  content.$destroy(true);
  content = null;
}

export default Toast
